<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box2">
            <div class="header">
                <Step
                    ref="stepRef"
                    :current-step="currentStep"
                    :steps-label="stepsLabel"
                    :total-steps="stepsLabel.length" />
            </div>
            <div class="container">
                <div class="content">
                    <div class="left_box">
                        <!-- 活动信息 -->
                        <div v-show="currentStep == 1">
                            <ActivityNews
                                ref="ActivityInfoRef"
                                :prize-info="prizeInfo"
                                :page-type="pageType"
                                :group_id="group_id"
                                @submit="getInfo" />
                        </div>
                        <!-- 红包设定 -->
                        <div v-show="currentStep == 2">
                            <RedEnvelopeSetting
                                ref="RedEnvelopeSettingRef"
                                :prize-info="prizeInfo"
                                :eff-date="effDate"
                                :page-type="pageType"
                                @submit="getInfo" />
                        </div>
                        <!-- 红包规则 -->
                        <div v-show="currentStep == 3">
                            <RedEnvelopeRule
                                ref="RulesPriRef"
                                :eff-date="effDate"
                                :page-type="pageType"
                                @submit="getInfo" />
                        </div>
                        <!-- 分享海报 -->
                        <div v-show="currentStep == 4">
                            <Posters ref="PostersRef" :page-type="pageType" :current-step="currentStep" />
                        </div>
                        <!-- 欢迎语 -->
                        <div v-show="currentStep == 5"><Welcome ref="WelcomeRef" :page-type="pageType" /></div>
                    </div>
                    <div v-if="currentStep !== 4 && currentStep !== 5" class="right_box">
                        <ActivityPhone :form-info="formInfo" :tiems="tiems" />
                        <!-- <MobilePhone :formInfo="formInfo" :tiems="tiems" /> -->
                    </div>
                </div>
                <!-- <div class="test-phone-preview">
      <PhonePreview>
        <div class="preview-box" v-for="item in list" :key="item">{{item}}ppooiiuuyyttrree</div>
      </PhonePreview>
    </div> -->
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button v-if="currentStep == 1" @click="onCancel">取消</el-button>
            <el-button v-else @click="onStep">上一步</el-button>
            <el-button v-if="currentStep != 5" type="primary" @click="onNext(currentStep)">下一步</el-button>
            <el-button v-else type="primary" @click="onPreserve">{{ pageType == 'look' ? '返回' : '保存' }}</el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import Step from '@/components/Step.vue';
import ActivityNews from './components/ActivityNews.vue';
import RedEnvelopeSetting from './components/RedEnvelopeSetting.vue';
import RedEnvelopeRule from './components/RedEnvelopeRule.vue';
import { getFissionAdd, fissionInfo, fissionEdit } from '@/api/smartMarketing/envelopesFission';
import MobilePhone from './components/MobilePhone.vue';
import Posters from './components/Posters.vue';
import Welcome from './components/Welcome.vue';
import PhonePreview from '@/components/zw/phonePreview/activityPhonePreview/index.vue';
import ActivityPhone from '@/components/zw/phonePreview/activityPhonePreview/envelopesFission/index.vue';
import { FormInstance, FormRules, ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { getSetionId } from '@/utils/utils';
import { onMounted, ref, nextTick, computed } from 'vue';
import { useStore } from '@/store';
const store = useStore();
const router = useRouter();
const route = useRoute();
/* const formInfo = ref({
    title: '',
    red_envelope_money: '',
    first_value: [],
    help_num: '',
    first_type: '',
    effect_date: ''
  }) */
const group_id = ref(Number(route.query?.group_id));
const formInfo = ref({
    /* 步骤1 */
    title: '',
    official_account_id: '', //公众号授权的ID
    activity_name: '', //活动名称
    group_id: 0, //分组id
    period_type: 1, //活动有效期类型: 1-永久 2-固定期限
    end_date: '', //结束时间
    begin_date: '', //开始时间
    description: '', //活动说明
    effect_date: [],
    // 步骤2
    red_envelope_money: '', //红包金额
    first_type: 1, //首拆类型 1-固定 2-随机金额 3-随机比例
    first_value: ['', ''], //值 固定[1] 随机金额比例 [2,3]
    help_num: '', //助力人数
    help_money_type: 1, //助力拆金额类型 1-固定 2-随机金额 3-随机比例
    help_money_value: ['', ''], //值 固定[1] 随机金额比例 [2,3]
    fission_num: '', //裂变次数
    red_envelope_total: '', //活动总金额
    // 步骤3
    customer_type: 1, //客户限制 1-不限 2-新客户
    help_type: 1, //助力者限制 1-不限 2-新客户
    help_num_type: 1, //助力次数 1-不限 2-限制
    help_num_value: 10, //help_num_type为2 必填
    customer_gender: 1, //性别限制 1-不限 2-男性 3女性
    limit_address_type: 1, //地区限制 1-不限 2-部分地区
    limit_address_value: [] //limit_address_type为2 必填
});
let pageType = route.query.type;
const stepRef: any = ref(null);
const ActivityInfoRef: any = ref(null);
const RedEnvelopeSettingRef: any = ref(null);
const PostersRef: any = ref(null);
const WelcomeRef: any = ref(null);
const RulesPriRef: any = ref(null);

const stepsLabel: any = ref([
    { title: '活动设置', stepIndex: 1 },
    { title: '红包设定', stepIndex: 2 },
    { title: '红包规则', stepIndex: 3 },
    { title: '分享海报', stepIndex: 4 },
    { title: '引流设置', stepIndex: 5 }
]);
const currentStep = ref(1);
const onStep = () => {
    currentStep.value--;
    stepRef.value.back();
};
const scrollbarRef = ref<any>(null);
/**
 * @description: 滚动到顶部
 */
const setScrollTopHandle = () => {
    nextTick(() => {
        scrollbarRef.value?.setScrollTop(0);
    });
};
const onNext = async (curStep: number) => {
    if (pageType == 'look') {
        currentStep.value == 5 && onRouter();
        currentStep.value++;
        stepRef.value.next();
        setScrollTopHandle();
        return;
    }
    if (curStep == 1) {
        // 活动信息
        if (!ActivityInfoRef.value.formRef) return;
        await ActivityInfoRef.value.formRef.validate((valid: any, fields: any) => {
            if (valid) {
                currentStep.value++;
                stepRef.value.next();
                setScrollTopHandle();
            }
        });
    }
    if (curStep == 2) {
        // 红包设定
        if (!RedEnvelopeSettingRef.value.formRef) return;
        await RedEnvelopeSettingRef.value.formRef.validate((valid: any, fields: any) => {
            if (valid) {
                currentStep.value++;
                stepRef.value.next();
                setScrollTopHandle();
            } else {
                // 最大值不合法
                if (fields.hasOwnProperty('red_envelope_total')) {
                    ElMessage.error('红包总金额不得超过10万元');
                } else {
                    ElMessage.error('请填完必填项');
                }
            }
        });
    }
    if (curStep == 3) {
        currentStep.value++;
        stepRef.value.next();
    }
    if (curStep == 4) {
        if (
            // 1: 海报库需要上传海报库id，2： 本地上传需要有url，0: 默认海报直接通过。因为会给个默认的url给后端
            (PostersRef.value.formData.poster.poster_type == 1 && PostersRef.value.formData.poster.poster_id != '') ||
            (PostersRef.value.formData.poster.poster_type == 2 &&
                PostersRef.value.formData.poster.absolute_url != '') ||
            PostersRef.value.formData.poster.poster_type === 0
        ) {
            if (PostersRef.value.formData.poster.desc_flag === 1 && !PostersRef.value.formData.poster.desc) {
                ElMessage.error('请填完必填项');
                return;
            }
            currentStep.value++;
            stepRef.value.next();
        } else {
            ElMessage.error('请填完必填项');
        }
    }
};
const onRouter = () => {
    store.dispatch('setGroupId', ActivityInfoRef.value.formData.group_id);
    router.back();
};
const onPreserve = async () => {
    if (pageType == 'look') {
        onRouter();
        return;
    }
    if (!WelcomeRef.value.formRef) return;
    await WelcomeRef.value.formRef.validate(async (valid: any, fields: any) => {
        if (valid) {
            // 删除数组第二个元素
            RedEnvelopeSettingRef.value.formData.first_type == 1 &&
                RedEnvelopeSettingRef.value.formData.first_value.splice(1, 1);
            RedEnvelopeSettingRef.value.formData.help_money_type == 1 &&
                RedEnvelopeSettingRef.value.formData.help_money_value.splice(1, 1);
            const position = PostersRef.value.getPostersInfo().position;
            const posterForm = PostersRef.value.formData;
            posterForm.poster.position = position;
            const params = {
                ...ActivityInfoRef.value.formData,
                ...RedEnvelopeSettingRef.value.formData,
                ...RulesPriRef.value.formData,
                ...posterForm,
                ...WelcomeRef.value.formData
            };
            pageType ? await fissionEdit({ activity_id: route.query.id, ...params }) : await getFissionAdd(params);
            const query = { group_id: params.group_id };
            router.push({
                name: 'SMART_MARKETING_FISSION_ENVELOPES_FISSION',
                params: query,
                query
            });
            ElMessage.success(pageType ? '编辑' : '新建' + '成功');
        } else {
            ElMessage.error('请填完必填项');
        }
    });
};
const onCancel = () => {
    const params = {
        ...ActivityInfoRef.value.formData
    };
    const query = { group_id: params.group_id };
    router.push({
        name: 'SMART_MARKETING_FISSION_ENVELOPES_FISSION',
        params: query
    });
};
// 查看
const getLook = async () => {
    const res = await fissionInfo({ activity_id: route.query.id });
    ActivityInfoRef.value.formData = {
        id: res.id,
        nick_name: res.nick_name,
        head_img: res.head_img,
        service_type_info: res.service_type_info,
        official_account_id: res.official_account_id,
        activity_name: res.activity_name,
        activity_type: res.activity_type,
        group_id: res.group_id,
        period_type: res.period_type,
        effect_date: res.effect_date,
        // 标题
        description: res.description,
        welcome_switch: res.welcome_switch
    };
    ActivityInfoRef.value.publicInfo = {
        name: res.nick_name,
        url: res.head_img,
        type: res.service_type_info
    };
    RedEnvelopeSettingRef.value.formData = {
        red_envelope_money: res.red_envelope_money,
        first_type: res.first_type,
        first_value: res.first_value,
        help_num: res.help_num,
        help_money_type: res.help_money_type,
        help_money_value: res.help_money_value,
        fission_num: res.fission_num,
        red_envelope_total: res.red_envelope_total
    };
    setTimeout(() => {
        formInfo.value.title = res.activity_name;
        formInfo.value.effect_date = res.effect_date;
        formInfo.value.red_envelope_money = res.red_envelope_money;
        formInfo.value.first_value = res.first_value;
        formInfo.value.help_num = res.help_num;
        formInfo.value.first_type = res.first_type;
    });
    RulesPriRef.value.formData = {
        customer_type: res.customer_type,
        help_type: res.help_type,
        help_num_type: res.help_num_type,
        help_num_value: res.help_num_value,
        limit_address_type: res.limit_address_type,
        limit_address_value: res.limit_address_value
    };
    // 处理海报回显示
    if (res.poster.poster_type == 1) {
        res.poster.poster_absolute_url = res.poster.absolute_url;
    } else if (res.poster.poster_type == 2) {
        res.poster.local_absolute_url = res.poster.absolute_url;
    }
    PostersRef.value.formData = {
        poster: res.poster
    };
    PostersRef.value.setPosition(res.poster.position);
    WelcomeRef.value.AllTags = res.winning_value;
    WelcomeRef.value.creators = res.employee_ids;
    Object.assign(WelcomeRef.value.formData, {
        employee_ids: getSetionId('id', res.employee_ids),
        activity_image: res.activity_image,
        content: res.content,
        title: res.title,
        desc: res.desc,
        welcome_switch: res.welcome_switch,
        winning_value: getSetionId('id', res.winning_value),
        welcome_type: res.type
    });
    WelcomeRef.value.onLookData(res);
    RedEnvelopeSettingRef.value.setComputed();
};
onMounted(() => {
    pageType = route.query.type;
    if (pageType) {
        getLook();
    }
});
const formatDuring = micro_second => {
    const second = Math.floor(micro_second / 1000);
    // 天数
    const day = Math.floor(second / 3600 / 24);
    // 小时
    const hr = Math.floor((second / 3600) % 24);
    // 分钟
    const min = Math.floor((second / 60) % 60);
    // 秒
    const sec = Math.floor(second % 60);
    return day + '天' + hr + '小时' + min + '分钟' + sec + '秒';
};
const tiems = ref('');
const getInfo = (v: any) => {
    Object.assign(formInfo.value, v);
    if (v.activity_name) {
        formInfo.value.title = v.activity_name;
    }

    if (formInfo.value.period_type == 2) {
        if (formInfo.value.effect_date && formInfo.value.effect_date.length !== 0) {
            const dateTime = Date.parse(formInfo.value.effect_date[0]);
            const dateTimes = Date.parse(formInfo.value.effect_date[1]);
            const time = dateTimes - dateTime;
            tiems.value = formatDuring(time);
        }
    } else {
        tiems.value = '';
    }
};
</script>
<style lang="scss" scoped>
.header {
    padding: 21px;
    border: 1px solid #eaeaea;
    border-top: none;
    border-radius: 1px;
    box-shadow: 0 4px 4px 1px rgb(240 240 240 / 50%);
    background: #fff;
    margin-bottom: 16px;
    box-sizing: border-box;
}

.container {
    padding: 24px;
    box-sizing: border-box;
    box-shadow: 0 4px 4px 1px rgb(240 240 240 / 50%);
    border-radius: 1px;
    opacity: 1;
    border: 1px solid #eaeaea;
    border-bottom: none;
    background: #fff;

    .content {
        display: flex;

        .left_box {
            width: 100%;

            // width: 60%;
        }

        .right_box {
            display: flex;
            justify-content: center;
            width: 40%;
            padding-bottom: 10px;
        }
    }

    .btn_box {
        padding-top: 13px;
        text-align: center;
        border-top: 1px solid #d9d9d9;
    }
}
</style>
